package com.xhis.homenurse.webservice.convert;

import android.util.Log;

import com.xhis.homenurse.tools.LogUtil;
import com.xhis.homenurse.webservice.ksoap2.SoapEnvelope;
import com.xhis.homenurse.webservice.ksoap2.serialization.SoapObject;
import com.xhis.homenurse.webservice.ksoap2.transport.SoapHelper;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * @author panghuan
 * create at 18/3/22 下午2:06
 */
public final class SoapResponseBodyConverter<T> implements Converter<ResponseBody, T>
{
    private String TAG = getClass().getSimpleName();

    private Class<?> clazz;

    protected SoapResponseBodyConverter(Type clazz) {
        this.clazz = (Class<?>) clazz;
    }

    @Override
    public T convert(ResponseBody value) throws IOException
    {
        SoapEnvelope soapEnvelope = SoapHelper.getInstance().getSoapEnvelope();
        SoapHelper.getInstance().parseResponse(soapEnvelope,value.byteStream());
        SoapObject resultsRequestSOAP = (SoapObject) soapEnvelope.bodyIn;
        resultsRequestSOAP = (SoapObject) resultsRequestSOAP.getProperty(0);
        // 以String形式得到参数
        String outXml = "";
        for (int i = 0; i < resultsRequestSOAP.getPropertyCount(); i++) {
            outXml += resultsRequestSOAP.getPropertyAsString(i);
        }
        String log = resultsRequestSOAP.toString();
        Log.e(TAG, "ResponseBodyToStringConverterFactory : " + log);
        LogUtil.saveLog("response", log);
        try {
            //return adapter.fromJson(obj.toString());
            //return (T) obj.toString();
            Object resultObj = null;
            Method[] methods = clazz.getMethods();
            // 利用反射向不同类中的有相同方法名的方法中传入从服务器返回的outXml
            for (Method m : methods) {
                if (m.getName().equals("getOutData")) {
                    resultObj = clazz.newInstance();
                    m.invoke(resultObj, outXml);
                }
            }
            return (T) resultObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            value.close();
        }
    }
}
